package com.xmb.wcapi.shiro;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;

import com.alibaba.fastjson.JSONObject;
import com.xmb.wcapi.constant.R;

public class AppUserFilter extends UserFilter {

	/**
	 * 解决身份验证不通过根据ajax或web直接访问的返回问题
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		
		HttpServletRequest httpRequest = WebUtils.toHttp(request);
		
		if (httpRequest.getHeader("x-requested-with") != null && httpRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
			// 解决 WebUtils.toHttp 往返回response写数据跨域问题
			String origin = httpRequest.getHeader("Origin"); 
			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
			httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
			// 通过对 Credentials 参数的设置，就可以保持跨域 Ajax 时的 Cookie
			// 设置了Allow-Credentials，Allow-Origin就不能为*,需要指明具体的url域
			httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
			HttpServletResponse httpResponse = WebUtils.toHttp(response);
			httpResponse.setContentType("application/json; charset=utf-8");
			PrintWriter writer = httpResponse.getWriter();
			writer.print(JSONObject.toJSONString(R.error(5001,"未登录或登录信息已过期")));
			writer.flush();
			writer.close();
		}else {
			return super.onAccessDenied(httpRequest, response);
		}

		return false;
	}
}